package com.hsj.busmanager.service;

import com.hsj.busmanager.api.Bus;
import com.hsj.busmanager.api.Position;
import com.hsj.busmanager.mapper.BusMapper;
import com.hsj.busmanager.mapper.PositionMapper;
import com.hsj.busmanager.util.CommonUtil;
import com.hsj.busmanager.util.Page;
import com.hsj.busmanager.util.TabelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BusSerivce {
    @Autowired
    private BusMapper busMapper;

    @Autowired
    private PositionMapper positionMapper;

    public TabelData<Bus> getRentCostData(Page page, Bus bus) {

        TabelData tabelData = new TabelData();

        Integer start = (page.getPage()-1)*page.getLimit();

        List<Bus> busList = busMapper.getBusListPage(start,page.getLimit(),bus);

        if(busList!=null && busList.size()>0){
            for(Bus bus1:busList){
                bus1.setShowCreateTime(CommonUtil.getDateByFormat(bus1.getCreateTime(),"yyyy-MM-dd"));
                if(bus1.getDistanceMonth()!=null && bus1.getRentMoney()!=null){
                    bus1.setCost(bus1.getDistanceMonth()*(Double.valueOf(bus1.getRentMoney())));
                }
            }
        }


        int count = busMapper.getBusCount(bus);

        if (busList == null && busList.size() == 0) {
            return null;
        }

        tabelData.setCount(count);
        tabelData.setData(busList);

        return tabelData;

    }

    public Bus getBusById(Integer id) {
       return busMapper.selectByPrimaryKey(id);
    }

    public void deleteById(Integer id) {
        busMapper.deleteByPrimaryKey(id);
    }

    public void update(Bus bus) {
        busMapper.updateByPrimaryKeySelective(bus);
    }

    public void insert(Bus bus) {

        bus.setCreateTime(new Date());
        bus.setOwner(-1);
        bus.setDistanceMonth(0.00);
        busMapper.insert(bus);

        //生成该车辆的随机坐标
        Position position = new Position();
        position.setLat("0");
        position.setLon("0");
        position.setLastLon("0");
        position.setLastLat("0");
        position.setBusId(bus.getId());
        positionMapper.insert(position);

    }

    public List<Bus> getOnwerBusList() {

        return busMapper.getOnwerBusList();
    }
}
